package com.ja.openchat.ui.chat.ext;

import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.text.TextUtils;
import android.view.View;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;

import com.bumptech.glide.request.target.SimpleTarget;
import com.bumptech.glide.request.transition.Transition;
import com.ja.openchat.R;
import com.ja.openchat.ui.chat.ConversationFragment;
import com.ja.openchat.ui.chat.annotation.ExtContextMenuItem;
import com.ja.openchat.ui.chat.ext.core.ConversationExt;
import com.nanchen.compresshelper.CompressHelper;
import com.zhihu.matisse.filter.Filter;
import com.zy.openchat.App;
import com.zy.openchat.Constants;
import com.zy.openchat.core.manager.TelegramManager;
import com.zy.openchat.core.model.group.GroupSendInfo;
import com.zy.openchat.core.model.group.LocalMessageInfo;
import com.zy.openchat.core.model.message.ChatInfo;
import com.zy.openchat.core.model.video.UploadMedioInfo;
import com.zy.openchat.util.Common;
import com.zy.openchat.util.Glide4Engine;
import com.zy.openchat.util.MediaFile;
import com.zy.openchat.util.compress.util.VideoProgressListener;
import com.zy.openchat.util.glide.GlideApp;

import org.jetbrains.annotations.NotNull;

import java.io.File;
import java.util.ArrayList;
import java.util.List;

import io.reactivex.Observable;
import io.reactivex.ObservableEmitter;
import io.reactivex.ObservableOnSubscribe;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.functions.Action;
import io.reactivex.functions.Consumer;
import io.reactivex.schedulers.Schedulers;
import me.bzcoder.mediapicker.SmartMediaPickerex;
import me.bzcoder.mediapicker.config.Constant;
import me.bzcoder.mediapicker.config.MediaPickerEnum;
import me.goldze.mvvmhabit.base.BaseActivity;


public class AlbumExt extends ConversationExt {

    //https://github.com/BzCoder/SmartMediaPicker
    private final int max = Integer.MAX_VALUE;
    private int maxFileSize = max/ Filter.K/Filter.K;

    /**
     * @param containerView 扩展view的container
     * @param conversation
     */
    @ExtContextMenuItem
    public void pickImage(View containerView, ChatInfo conversation) {
        startActivityForResult(SmartMediaPickerex.builder(fragment)
                //最大图片选择数目 如果不需要图片 将数目设置为0
                .withMaxImageSelectable(9)
                //最大视频选择数目 如果不需要视频 将数目设置为0
                .withMaxVideoSelectable(1)
                //图片选择器是否显示数字
                .withCountable(true)
                //测试111
                .imageShowEditText(conversation.isSuperGroup()&&messageViewModel.canEditGroupSetting())
                //最大视频长度
                .withMaxVideoLength(max)
                //最大视频文件大小 单位MB
                .withMaxVideoSize(maxFileSize)
                //最大图片高度 默认1920
                .withMaxHeight(max)
                //最大图片宽度 默认1920
                .withMaxWidth(max)
                .captureAuthority(App.getInstanse().getPackageName() + ".utilcode.fileprovider")
                .captureDirectory(Constants.userImagePath())
                //最大图片大小 单位MB
                .withMaxImageSize(maxFileSize)
                //设置图片加载引擎
                .withImageEngine(new Glide4Engine())
                //前置摄像头拍摄是否镜像翻转图像
                .withIsMirror(false)
                //弹出类别，默认弹出底部选择栏，也可以选择单独跳转
                .withMediaPickerType(MediaPickerEnum.PHOTO_PICKER)
                .build()
                .getIntentForPicker(),Constant.REQUEST_CODE_CHOOSE);
    }

    private ProgressDialog progressDialog = null;
    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        if (resultCode == Activity.RESULT_OK&&data != null) {
            List<String> resultData = SmartMediaPickerex.getResultData(fragment.getContext(), requestCode, resultCode, data);
            List<String> remarkData = SmartMediaPickerex.getResultRemarkData(fragment.getContext(), requestCode, resultCode, data);
            GroupSendInfo temp = null;
            if(fragment instanceof ConversationFragment){
                temp = ((ConversationFragment)fragment).getGroupSendInfo();
            }
            final GroupSendInfo groupSendInfo = temp;
            progressDialog = null;
            if(resultData!=null&&resultData.size()>0){
                List<Observable<UploadMedioInfo>> observables = new ArrayList<>();
                for(int i = 0;i<resultData.size();i++){
                    String localPah = resultData.get(i);
                    final int index = i;
                    if (MediaFile.isVideoFileType(MediaFile.getFileType(localPah).fileType)){
                        if(progressDialog==null){
                            progressDialog = new ProgressDialog(fragment.getContext());
                            progressDialog.setTitle(null);
                            progressDialog.setCancelable(false);
                            progressDialog.setCanceledOnTouchOutside(false);
                            progressDialog.setMessage(fragment.getString(R.string.compressed_video_text));
                            progressDialog.setIndeterminate(false);
                            progressDialog.setMax(10000);
                            progressDialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
                            progressDialog.setProgress(0);
                            progressDialog.show();
                        }
                        observables.add(Observable.create(new ObservableOnSubscribe<UploadMedioInfo>() {
                            @Override
                            public void subscribe(@NotNull ObservableEmitter<UploadMedioInfo> emitter) throws Exception {
                                emitter.onNext(UploadMedioInfo.compressVideo(fragment.getActivity(), localPah, new VideoProgressListener() {
                                    UploadMedioInfo compress = UploadMedioInfo.newVideoProgress().withIndex(index);
                                    @Override
                                    public void onProgress(float progress) {
                                        compress.videoCompressProgress = progress*10000;
                                        emitter.onNext(compress);
                                    }
                                }).withIndex(index));
                                emitter.onComplete();
                            }
                        }));
                    }else{
                        observables.add(Observable.create(new ObservableOnSubscribe<UploadMedioInfo>() {
                            @Override
                            public void subscribe(@NotNull ObservableEmitter<UploadMedioInfo> emitter) throws Exception {
                                if(!TextUtils.isEmpty(localPah)&&(localPah.endsWith(".gif")||localPah.endsWith(".GIF"))){
                                    emitter.onNext(UploadMedioInfo.newImage(localPah).withIndex(index));
                                }else{
                                    File newFile = new CompressHelper.Builder(fragment.getActivity()).setMaxWidth(1440).setMaxHeight(2880).build().compressToFile(new File(localPah));
                                    emitter.onNext(UploadMedioInfo.newImage(newFile.getAbsolutePath()).withIndex(index));
                                }
                                emitter.onComplete();
                            }
                        }));
                    }
                }
                if(observables!=null&&observables.size()>0){
                    if(progressDialog==null){
                        ((BaseActivity)fragment.getActivity()).showProgress();
                    }
                    Observable.concat(observables)
                            .subscribeOn(Schedulers.newThread())
                            .observeOn(AndroidSchedulers.mainThread())
                            .subscribe(new Consumer<UploadMedioInfo>() {
                                @Override
                                public void accept(UploadMedioInfo first) throws Exception {
                                    if(first.isImage){
                                        GlideApp.with(activity)
                                                .asBitmap()
                                                .load(first.mediaPath)
                                                .into(new SimpleTarget<Bitmap>() {
                                                    @Override
                                                    public void onResourceReady(@NonNull Bitmap resource, @Nullable Transition<? super Bitmap> transition) {
                                                        if(conversation.isGroupSendChat()){
                                                            boolean isGif = first.mediaPath.endsWith(".gif")||first.mediaPath.endsWith(".GIF");
                                                            LocalMessageInfo.setResultIntent(activity,groupSendInfo
                                                                    ,LocalMessageInfo.buildMediaLocalMessage(isGif? TelegramManager.MessageType.MessageType_Animation: TelegramManager.MessageType.MessageType_Photo
                                                                            ,first.mediaPath
                                                                            ,messageViewModel.getBurnAfterCountDown()
                                                                            ,resource.getWidth(),resource.getHeight(),0));
                                                        }else{
                                                            messageViewModel.sendImgMsg(conversation
                                                                    ,!Common.isEmpty(remarkData)&&remarkData.size()>first.index?remarkData.get(first.index):null
                                                                    ,first.mediaPath
                                                                    ,resource
                                                                    ,resource.getWidth()
                                                                    ,resource.getHeight());
                                                        }

                                                    }
                                                });
                                    }else{
                                        if(first.isCompressFinish){
                                            if(conversation.isGroupSendChat()){
                                                LocalMessageInfo.setResultIntent(activity,groupSendInfo
                                                        ,LocalMessageInfo.buildMediaLocalMessage(TelegramManager.MessageType.MessageType_Video
                                                                ,first.mediaPath
                                                                ,messageViewModel.getBurnAfterCountDown()
                                                                ,first.width,first.height,first.duration));
                                            }else{
                                                messageViewModel.sendVideoMsg(conversation,first.mediaPath,first.duration,first.width,first.height);
                                            }

                                        }else{
                                            if(progressDialog!=null){
                                                progressDialog.setProgress((int)first.videoCompressProgress);
                                            }
                                        }

                                    }


                                }
                            }, new Consumer<Throwable>() {
                                @Override
                                public void accept(Throwable throwable) throws Exception {
                                    ((BaseActivity)fragment.getActivity()).hideProgress();
                                    if(progressDialog!=null){
                                        progressDialog.dismiss();
                                        progressDialog = null;
                                    }
                                    throwable.printStackTrace();
                                }
                            }, new Action() {
                                @Override
                                public void run() throws Exception {
                                    if(progressDialog!=null){
                                        progressDialog.dismiss();
                                        progressDialog = null;
                                    }
                                    ((BaseActivity)fragment.getActivity()).hideProgress();
                                }
                            });
                }

            }
        }
    }

    @Override
    public int priority() {
        return 1;
    }

    @Override
    public int iconResId() {
        return R.drawable.icon_photo;
//        return R.mipmap.menu_photo;
    }

    @Override
    public String title(Context context) {
        return context.getString(R.string.album_text);
    }

    @Override
    public String contextMenuTitle(Context context, String tag) {
        return title(context);
    }
}
